package com.spring.service;

import com.spring.dao.IBaseDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by hbl on 2017/12/27.
 */
@Service("baseService")
public class BaseServiceImp<T> implements IBaseService<T> {

    private IBaseDao<T> baseDao;

    public IBaseDao<T> getBaseDao() {
        return baseDao;
    }

    @Resource
    public void setBaseDao(IBaseDao<T> baseDao) {
        this.baseDao = baseDao;
    }

    public void setCls(Class<T> cls) {
        this.cls = cls;
    }

    /**
     * 创建一个Class的对象来获取泛型的class
     */
    private Class<T> cls;

    public Class<T> getCls() {
        //获取泛型的Class对象
        if (cls == null)
            return ((Class<T>)
                    (((ParameterizedType) (this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
        //   System.out.println("------>>>>>>" + cls.toString());
        return cls;
    }


    @Override
    public void add(T t) {
        this.baseDao.add(t);
    }

    @Override
    public void update(T t) {
        this.baseDao.update(t);
    }

    @Override
    public void delete(int id) {
        this.baseDao.delete(id);
    }

    @Override
    public T load(int id) {
        return this.baseDao.load(id);
    }

    @Override
    public List<T> listAll() {
        String hql = "from " + this.getCls().getName();
        System.out.println(hql);
        return this.baseDao.list(hql);
    }

}
